<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%
    //!add project
    //!find project
    //?edit project
%>
<html lang="ru">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta charset="utf-8">
        <link rel="stylesheet" href="../dojo/dijit/themes/soria/soria.css">
        <link rel="stylesheet" href="../dojo/dijit/themes/soria/soria.css" />
        <link rel="stylesheet" href="../dojo/dojox/grid/resources/Grid.css" />
        <link rel="stylesheet" href="../dojo/dojox/grid/resources/soriaGrid.css" />
        <script>dojoConfig = {parseOnLoad: true, isDebug: true}</script>
        <script src='../dojo/dojo/dojo.js'></script>
        <script>
            X = 0;
            idOfDelItem = 0;
            isSendForm = false;
            function gridReload(req) {
                req = "sel?param1=" + encodeURIComponent(req) + "";
                //debug
                if (req == "undefined") {
                    req = "";
                }
                //debug
                alert("req=" + req);
                dojo.byId("test1").innerHTML = req;
                dojo.require("dojox.grid.DataGrid");
                dojo.require("dojox.data.CsvStore");
                dojo.require("dijit.form.Button");
                require([
                    "dojo",
                    "dojo/_base/array",
                    "dojo/dom-construct",
                    "dojox/grid/DataGrid",
                    "dojo/store/Memory",
                    "dojo/data/ObjectStore",
                    "dojo/request",
                    "dojo/domReady!"
                ],
                        function(dojo, array, dom, DataGrid, Memory, ObjectStore, request) {
                            var getData = request.get(req, {
                                handleAs: "json"
                            });
                            getData.then(function(response) {
                                var container = dojo.byId("test");
                                container.innerHTML = "";
                                array.forEach(response.items, function(book, index) {
                                    dom.create("div", {"innerHTML": book.col1 + ":" + book.col5}, container);
                                });
                                grid1.store.close();
                                var store = new ObjectStore({objectStore: new Memory({data: response.items})});
                                grid1.setStore(store);
                                grid1.update();
                                grid1.sort();
                            });
                        }
                );
//alert('test done');
            }
            function getSearch() {
                gridReload(dojo.byId("dialogSearch_sdescr").value);
                alert('search:' + dojo.byId("dialogSearch_sdescr").value + " done.");
            }
        </script>
    </head>
    <!--DESCRIPTION
    =ADDPROJECT=
    FORM
            ![TEXT]NAMEOFPROJECT
            ![TEXT]STATEOFPROJECT
            ![TEXT]TYPEOFPROJECT
            !DEPARTMENT (load from json)
                    ![TEXT]LEVEL (APP/GOSB/OSB)
                    ![TEXT]UPRAVLENIE (UVSAS)
                    ![TEXT]FUNKBLOCK	(ADMIN BLOCK)
            ECEFFECT
                    [MONEYRUB]CALCULATED
                    [MONEYRUB]SUBMITTED
            REALISATIONTIME
                    [DATE]BEGIN
                    [DATE]END
            EXTENSIONS
                    [INT]IDOF4I
                    [FILE]FILES
                    [CHECKBOX]HIDDEN
            MANAGER
                    [TEXT]PSSMANGEROFPROJECT
    =/ADDPROJECT=
    =TOOLSFOR:ADDPROJECT
    INPUT
            TEXT
                    REQUARED
            DATE
                    REQUARED
            MONEY
                    REQUARED
            COMBOBOX
                    REQUARED
            CHECKBOX
                    REQUARED
    =/TOOLSFOR:ADDPROJECT
    -->
    <body class="soria">
        <!--MENU, maybe TABS-->
        <!--CREATEFORM-->
        <script type="text/javascript">
            dojo.require("dijit.Dialog");
            dojo.require("dijit.form.TextBox");
            dojo.require("dijit.form.TimeTextBox");
            dojo.require("dijit.form.Button");
            dojo.require("dijit.form.DateTextBox");
            dojo.require("dijit.form.FilteringSelect");
            dojo.require("dijit.form.CurrencyTextBox");
            function sendForm() {
                var form = dojo.byId("myForm");
                dojo.connect(form, "onsubmit", function(event) {
                    // Stop the submit event since we want to control form submission.
                    //alert(event);
                    dojo.stopEvent(event);
                    // The parameters to pass to xhrPost, the form, how to handle it, and the callbacks.
                    // Note that there isn't a url passed.  xhrPost will extract the url to call from the form's
                    //'action' attribute.  You could also leave off the action attribute and set the url of the xhrPost object
                    // either should work.
                    //debug
                    //alert("isSendForm:" + isSendForm);
                    if (isSendForm) {
                        var xhrArgs = {
                            form: dojo.byId("myForm"),
                            handleAs: "text",
                            load: function(data) {
                                dojo.byId("response").innerHTML = "Сохранено.";
                                gridReload('');
                                //!!!!!!!!dojo.byId("Dialog1").close();
                            },
                            error: function(error) {
                                // We'll 404 in the demo, but that's okay.  We don't have a 'postIt' service on the
                                // docs server.
                                dojo.byId("response").innerHTML = "Сохранено.";
                            }
                        }
                        // Call the asynchronous xhrPost
                        dojo.byId("response").innerHTML = "Сохранение..."
                        var deferred = dojo.xhrPost(xhrArgs);
                    }
                });
                isSendForm = false;
            }
            dojo.ready(sendForm);
            //dijit.byId('dialog1').hide();
            //alert("dialog 1");
        </script>
        <button dojoType="dijit.form.Button" onclick="dijit.byId('dialog1').show()">Добавить Проект</button>
        <div dojoType="dijit.Dialog" id="dialog1" title="Добавить Проект"
             execute="alert('submitted w/args:\n' + dojo.toJson(arguments[0], true));">
            <div data-dojo-type="dijit/form/Form" id="myForm" data-dojo-id="myForm"
                 encType="multipart/form-data" action="create" method="get">
                <script type="dojo/on" data-dojo-event="reset">
                    return confirm('Нажмите OK для очитки формы.');
                </script>
                <script type="dojo/on" data-dojo-event="submit">
                    if(this.validate()){
                    isSendForm=confirm('Добавить проект?');
                    //alert(isSendForm);
                    //var isSubmit = confirm('Form is valid, press OK to submit');
                    if (isSendForm){
                    //alert('dialog1 hide');
                    dijit.byId('dialog1').hide();}
                    return isSendForm;
                    }else{
                    alert('Форма неверно заполнена.');
                    //break;
                    isSendForm=false;
                    return false;
                    }
                    return true;
                </script>
                <table>
                    <tr>
                        <td></td>
                        <td></td>
                        <td ><label for="username">Пользователь: </label></td>
                        <!--td colspan="3" align="center"-->
                        <td align="center">
                            <!--input dojoType="dijit.form.TextBox" type="text" name="nameproj" id="nameproj"-->
                            <!--debug-->
                            <input data-dojo-type="dijit/form/ValidationTextBox" type="text" width="100%"  required="true" name="username" id="username" disabled='disabled' value="<%= request.getRemoteUser()%>">
                        </td>
                    </tr>
                    <tr>
                        <td ><label for="nameproj">Название: </label></td>
                        <td colspan="3" align="center">
                            <!--input dojoType="dijit.form.TextBox" type="text" name="nameproj" id="nameproj"-->
                            <!--debug-->
                            <input data-dojo-type="dijit/form/ValidationTextBox" type="text" style="width:100%"  required="true" name="param1" id="param1">
                        </td>
                    </tr>
                    <tr>
                        <td><label for="stateproj">Статус: </label></td>
                        <td><!--input dojoType="dijit.form.TextBox" type="text" name="stateproj" id="stateproj"-->
                            <select  dojoType="dijit.form.FilteringSelect"
                                     id="stateproj"
                                     name="stateproj"
                                     autoComplete="true"
                                     invalidMessage="Invalid state name"
                                     onChange="dojo.byId('stateproj_').value = arguments[0]"
                                     >
                                <option value="blank"></option>
                                <option value="done">завершен</option>
                                <option value="realised">реализован</option>
                                <option value="improve">на реализации</option>
                                <option value="developming">в разработке</option>
                            </select>
                        </td>
                        <!--/tr>
                        <tr-->
                        <td><label for="date">Тип: </label></td>
                        <td><!--input dojoType="dijit.form.DateTextBox" type="text" name="date" id="date"-->
                            <select  dojoType="dijit.form.FilteringSelect"
                                     id="typeproj"
                                     name="typeproj"
                                     autoComplete="true"
                                     invalidMessage="Invalid state name"
                                     onChange="dojo.byId('typeproj_').value = arguments[0]"
                                     >
                                <option value="blank"></option>
                                <option value="bri">БРИ</option>
                                <option value="kidzen">КАЙДЗЕН</option>
                                <option value="pssproj">ПСС-проект</option>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td><label for="date">Уровень: </label></td>
                        <td>
                            <!--input dojoType="dijit.form.TimeTextBox" type="text" name="time" id="time"-->
                            <select  dojoType="dijit.form.FilteringSelect"
                                     id="levelproj"
                                     name="levelproj"
                                     autoComplete="true"
                                     invalidMessage="Invalid state name"
                                     onChange="dojo.byId('levelproj_').value = arguments[0]"
                                     >
                                <option value="blank"></option>
                                <option value="app">аппарат СКБ</option>
                                <option value="gosb">ГОСБ</option>
                                <option value="osb">ОСБ</option>
                            </select>
                        </td>
                        <!--/tr>
                                <tr-->
                        <td><label for="date">Функ. блок: </label></td>
                        <td>
                            <select  dojoType="dijit.form.FilteringSelect"
                                     id="funcbproj"
                                     name="funcbproj"
                                     autoComplete="true"
                                     invalidMessage="Invalid state name"
                                     onChange="dojo.byId('funcbproj_').value = arguments[0]"
                                     >
                                <option value="blank"></option>
                                <option value="app">административный</option>
                                <option value="gosb">не административный</option>
                                <option value="osb">ОСБ</option>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td><label for="date">Управление: </label></td>
                        <td>
                            <!--input dojoType="dijit.form.TimeTextBox" type="text" name="time" id="time"-->
                            <select  dojoType="dijit.form.FilteringSelect"
                                     id="uprproj"
                                     name="uprproj"
                                     autoComplete="true"
                                     invalidMessage="Invalid state name"
                                     onChange="dojo.byId('uprproj_').value = arguments[0]"
                                     >
                                <option value="blank"></option>
                                <option value="app">УВиСАС</option>
                                <option value="gosb">УТСиТ</option>
                                <option value="osb">ОСБ</option>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td><label for="desc">Ожидаемый эффект: </label></td>
                        <td>
                            <!--input dojoType="dijit.form.CurrencyTextBox" name="desc" id="desc"-->
                            <!--input type="text" name="ecefcalc" id="ecefcalc" value="0.0" required="true"
                        data-dojo-type="dijit/form/CurrencyTextBox"
                        data-dojo-props="constraints:{fractional:false},
                        currency:'RUB',
                        invalidMessage:'Invalid amount. Cents are required.'" /-->
                            <!--debug-->
                            <input type="text" name="param2" id="param2" required="true"  value="0.0" required="true"
                                   data-dojo-type="dijit/form/CurrencyTextBox"
                                   data-dojo-props="constraints:{fractional:false},
                                   currency:'RUB',
                                   invalidMessage:'Invalid amount. Cents are required.'" />  
                        </td>
                    </tr>
                    <tr>
                        <td><label for="desc">Подтвержденный эффект: </label></td>
                        <td>
                            <!--input dojoType="dijit.form.CurrencyTextBox" name="desc" id="desc"-->
                            <input type="text" name="ecefsubm" id="ecefsubm" value="0.0" required="true"
                                   data-dojo-type="dijit/form/CurrencyTextBox"
                                   data-dojo-props="constraints:{fractional:true},
                                   currency:'RUB',
                                   invalidMessage:'Invalid amount. Cents are required.'" />  
                        </td>
                    </tr>
                    <tr>
                        <td><label for="desc">Начало проекта: </label></td>
                        <td>
                            <input type="text" id="projstartdate" name="projstartdate" required="false"  data-dojo-type="dijit/form/DateTextBox"/>
                        </td>
                    </tr>
                    <tr>
                        <td><label for="desc">Завершеение проекта: </label></td>
                        <td>
                            <input type="text" id="projstopdate" name="projstopdate" required="false"  data-dojo-type="dijit/form/DateTextBox"/>
                        </td>
                    </tr>
                    <tr>
                        <td><label for="desc">id в 4i : </label></td>
                        <td>
                            <input type="text" id="id4i" name="id4i" data-dojo-type="dijit/form/TextBox"/>
                        </td>
                    </tr>
                    <tr>
                        <td><label for="desc">скрыть запись: </label></td>
                        <td>
                            <input type="text" id="hide" name="hide" required="false"  data-dojo-type="dijit/form/CheckBox"/>
                        </td>
                    </tr>
                    <tr>
                        <td colspan="2" align="center">
                    </tr>
                </table>
                <button dojoType="dijit.form.Button" type="submit">OK</button></td>
                <!--button data-dojo-type="dijit/form/Button" type="button" onClick="console.log(myForm.getValues())">Get Values from form!</button-->
                <!--button data-dojo-type="dijit/form/Button" type="submit"onClick="" name="submitButton" value="Submit">Зарегестрировать</button-->
                <button data-dojo-type="dijit/form/Button" type="reset">Сброс</button>
            </div> 
            <div id="response" name="response"></div>
        </div>
        <!--/CREATEFORM-->
        <!--TABLE OF SEARCHE RESULT-->
        <button dojoType="dijit.form.Button" onclick="dijit.byId('dialogSearch').show()">Найти</button>
        <button data-dojo-type="dijit/form/Button" type="submit" onClick="gridReload('')">Обновить</button>
        <!--SEARCHFORM-->
        <div dojoType="dijit.Dialog" id="dialogSearch" title="Найти" >
            Поиск
            <input type="text" id="dialogSearch_sdescr" name="dialogSearch_sdescr" data-dojo-type="dijit/form/TextBox"/>
            <button dojoType="dijit.form.Button" type="submit" onClick="getSearch()" >Найти</button></td>
        <button data-dojo-type="dijit/form/Button" type="reset">Сброс</button>
    </div>
    <!--EDIT RECORD -->
    <div data-dojo-type="dijit.form.Button">
        Редактировать
        <script type="dojo/method" data-dojo-event="onClick" data-dojo-args="evt">
            var items = grid1.selection.getSelected();
            if(items.length){
            dojo.forEach(items, function(selectedItem){
            if(selectedItem !== null){
                dojo.forEach(grid1.store.getAttributes(selectedItem), function(attribute){
                var value = grid1.store.getValues(selectedItem, attribute);
                if (attribute=='col2'){
                    dijit.byId('param1').set('value',value);
                    alert('col2: ' + attribute + ', value: ' + value);
                }
                if (attribute=='col1'){
                idOfDelItem=parseInt(value);
                alert('col1:' + attribute + ', value: ' + value);
                }
            }); // end forEach
            //TASK
            //send to create dialog information about deletion of that item
            
            dijit.byId('dialog1').show();
            } // end if
            }); // end forEach
            } // end if
        </script>
    </div>
    <!--/SEARCHFORM-->
    <div id="grid" ></div>
    <!-- load dojo and provide config via data attribute -->
    <!--script src="../dojo/dojo/dojo.js" data-dojo-config="isDebug: true, async: true"></script-->
    <script>
            dojo.require("dojox.grid.DataGrid");
            dojo.require("dojox.data.CsvStore");
            dojo.require("dijit.form.Button");
            require([
                "dojox/grid/DataGrid",
                "dojo/store/Memory",
                "dojo/data/ObjectStore",
                "dojo/request",
                "dojo/domReady!"
            ], function(DataGrid, Memory, ObjectStore, request) {
                var dataStore;
                //request.get("hof-batting.json", {
                request.get("sel?param1=", {
                    handleAs: "json"
                }).then(function(data) {
                    dataStore = new ObjectStore({objectStore: new Memory({data: data.items})});
                    grid1 = new DataGrid({
                        store: dataStore,
                        query: {id: "*"},
                        clientSort: true,
                        clearOnClose: true,
                        rowSelector: '10px',
                        selectionMode: 'single',
                        queryOptions: {},
                        structure: [
                            {name: "ID", field: "col1", width: "5%"},
                            {name: "SDESCR", field: "col2", width: "35%"},
                            {name: "DESCR", field: "col3", width: "10%"},
                            {name: "CTIME", field: "col4", width: "25%"},
                            {name: "MTIME", field: "col5", width: "25%"},
                        ]

                    }, "grid");
                    grid1.startup();
                });
            });
    </script>
    <div id="test">
        test
    </div>
    <div id="test1">
        test1
    </div>
    <b>Result</b>
    <div id="response"></div>
</body>
</html>